package com.example.demo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.example.demo.common.GetMessageCode;
import com.example.demo.pojo.Coupon;
import com.example.demo.pojo.Member;
import com.example.demo.pojo.User;
import com.example.demo.pojo.Usercoupon;
import com.example.demo.service.CouponService;
import com.example.demo.service.MemberService;
import com.example.demo.service.UserCouponService;
import com.example.demo.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@Api(value = "前台用户",tags = "前台用户")
public class usercontroller {
    //用户
    @Autowired
    private UserService userService;

    //对redis操作类
    @Autowired
    private RedisTemplate<String ,String> redisTemplate;

    //会员
    @Autowired
    private MemberService memberService;

    //优惠卷
    @Autowired
    private CouponService couponService;

    //用户优惠卷
    @Autowired
    private UserCouponService userCouponService;

    //获取验证码
    @ApiOperation(value = "获取验证码",notes = "获取验证码")
    @ApiImplicitParams({@ApiImplicitParam(name = "CellPhoneNumber",value = "手机号/新的手机号")})
    @RequestMapping(value = "/GetTheAuthenticationCode",method = RequestMethod.POST)
    public String GetTheAuthenticationCode(String CellPhoneNumber){
        String TheAuthenticationCode = GetMessageCode.getCode(CellPhoneNumber);
        if (TheAuthenticationCode.equals("00000")){
            return "验证码发送失败，请稍后再试";
        }else {
            //将手机号和验证码存在redis里，时效 2分钟
            redisTemplate.opsForValue().set(CellPhoneNumber,TheAuthenticationCode,2, TimeUnit.MINUTES);
            return "验证码发送成功，请查看手机短信";
        }
    }

    //登陆
    @ApiOperation(value = "登陆",notes = "登陆")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "CellPhoneNumber",value = "手机号"),
            @ApiImplicitParam(name = "TheAuthenticationCode",value = "验证码")
    })
    @RequestMapping(value = "login",method = RequestMethod.POST)
    public String login(String CellPhoneNumber, String TheAuthenticationCode, HttpSession httpSession){
        //通过手机号去查找redis里的验证码
        String TheAuthenticationCode1=redisTemplate.opsForValue().get(CellPhoneNumber);
        //比较验证码是否相同
        if (TheAuthenticationCode.equals(TheAuthenticationCode1)){
            //通过验证码去数据库查询是否存在该用户
            List<User> userList=userService.selectByphonenumber(CellPhoneNumber);
            if (userList.size()==0){
                User user=new User();
//                Integer flag=Integer.valueOf(CellPhoneNumber);
                user.setPhonenumber(CellPhoneNumber);
                //新增用户
                int i=userService.insert(user);
                //判断是否新增用户成功
                if (i<=0){
                    return "网络连接超时！";
                }else {
                    //通过新增用户的手机号查询
                    List<User> list=userService.selectByphonenumber(CellPhoneNumber);
                    //获取新增用户对象
                    User user1=list.get(0);
                    //创建会员对象
                    Member member=new Member();
                    //创建时间对象
                    Date date=new Date();
                    //创建时间格式对象
                    SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    //规定时间格式
                    String da=simpleDateFormat.format(date);
                    try {
                        date=simpleDateFormat.parse(da);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    member.setStarttime(date);
                    member.setUserid(user1.getUserid());
                    //计算7天后的时间索
                    long rightTime = (long) (date.getTime() + 7*24 * 60 * 60 * 1000);
                    String newtime = simpleDateFormat.format(rightTime);
                    try {
                        member.setDuetime(simpleDateFormat.parse(newtime));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    //赠送7天体验会员
                    while (true){
                        int time=memberService.insert(member);
                        if (time>0){
                            break;
                        }
                    }
                    List<Coupon> couponList=couponService.selectByType("新人专属");
                    if (couponList.size()>0){
                        for (Iterator<Coupon> iterator=couponList.iterator();iterator.hasNext();) {
                            Coupon coupon=iterator.next();
                            Long.valueOf((Long.valueOf(coupon.getEffectivetime()))*24*60*60*1000);
                            long rig=(long)(date.getTime()+coupon.getEffectivetime()*24*60*60*1000);
                            String newe=simpleDateFormat.format(rig);
                            Usercoupon usercoupon=new Usercoupon();
                            usercoupon.setCouponid(coupon.getCouponid());
                            usercoupon.setUserid(user1.getUserid());
                            usercoupon.setStarttrme(date);
                            try {
                                usercoupon.setEndtrme(simpleDateFormat.parse(newe));
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                            while (true){
                                int i1=userCouponService.insert(usercoupon);
                                if (i1>0){
                                    break;
                                }
                            }
                        }
                    }
                    httpSession.setAttribute("user",user1);
                }
            }else {
                httpSession.setAttribute("user",userList.get(0));
            }
            return "登陆成功";
        }else {
            return "验证码输入错误";
        }
    }

    //更换手机号
    @ApiOperation(value = "更改手机号码",notes = "更改手机号码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "usedPhoneNumber",value = "旧的手机号码"),
            @ApiImplicitParam(name = "newPhoneNumber",value = "新的手机号码"),
            @ApiImplicitParam(name = "TheAuthenticationCode",value = "验证码")
    })
    @RequestMapping(value = "/changePhoneNumber",method = RequestMethod.POST)
    public String changePhoneNumber(String usedPhoneNumber,String newPhoneNumber,String TheAuthenticationCode){
        //通过新的手机号去查找redis里面的验证码
        String TheAuthenticationCode1=redisTemplate.opsForValue().get(newPhoneNumber);
        //比较两次的验证码
        if (TheAuthenticationCode.equals(TheAuthenticationCode1)){
            //通过新手机号去查询该手机号码是否绑定
            List<User> userList=userService.selectByphonenumber(newPhoneNumber);
            if (userList.size()!=0){
                return "该手机号以注册，不能更换";
            }
            //通过旧手机号查询用户信息
            List<User> userList1=userService.selectByphonenumber(usedPhoneNumber);
            User user=userList1.get(0);
            user.setPhonenumber(newPhoneNumber);
            int i=userService.updateByUserId(user);
            if (i>0){
                return "以更换手机号码";
            }else {
                return "更换手机号码失败";
            }

        }else {
            return "验证码输入错误";
        }
    }

    //设置支付密码验证手机号
    @ApiOperation(value = "支付密码验证手机号",notes = "支付密码验证手机号")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "CellPhoneNumber",value = "手机号码"),
            @ApiImplicitParam(name = "TheAuthenticationCode",value = "验证码")
    })
    @RequestMapping(value = "/SettingPaymentPassword",method = RequestMethod.POST)
    public String SettingPaymentPassword(String CellPhoneNumber,String TheAuthenticationCode){
        String TheAuthenticationCode1=redisTemplate.opsForValue().get(CellPhoneNumber);
        if (TheAuthenticationCode.equals(TheAuthenticationCode1)){
            return "验证码正确";
        }else {
            return "验证码输入错误";
        }
    }

    //
    @ApiOperation(value = "设置支付密码",notes = "设置支付密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "CellPhoneNumber",value = "手机号码"),
            @ApiImplicitParam(name = "PaymentPassword",value = "支付密码")
    })
    public String SettingPaymentPwd(String CellPhoneNumber,String PaymentPassword){
        List<User> userList=userService.selectByphonenumber(CellPhoneNumber);
        User user=userList.get(0);
        user.setPaymentpassword(PaymentPassword);
        int i=userService.updateByUserId(user);
        if (i>0){
            return "设置支付密码成功";
        }else {
            return "设置支付密码失败";
        }
    }

    //用户登陆信息
    @ApiOperation(value = "用户登陆信息",notes = "用户登陆信息")
    public String User(HttpSession httpSession){
        User user=(User) httpSession.getAttribute("user");
        if (user!=null){
            return JSONArray.toJSONString(user);
        }
        return "请先登录";
    }

    //查看会员信息
    @ApiOperation(value = "查看会员信息",notes = "查看会员信息")
    //@ApiImplicitParam(name = "userId",value = "用户id")
    @RequestMapping(value = "/selectMember",method = RequestMethod.POST)
    public String selectMember(HttpSession httpSession){
        User user=(User) httpSession.getAttribute("user");
            int flag=user.getMember();
            if (flag==0){
              Member member= memberService.selectByUid(user.getUserid());
              //得到会员结束时间
              long endTime=member.getDuetime().getTime()-8*60*60*24*1000;
              Date date=new Date();
              //得到当前时间
              long nowTime=date.getTime();
              long time=endTime-nowTime;
              if (time<=0){
                  return "你的会员今天到期";
              }
              if (time<24*60*60*1000){
                  return "你的会员今天到期";
              }
              //把时间戳转换成秒
              long time2=time/1000;
              //计算剩余多少天
              if (time2 % (60*60*24)!=0){
                 long day=time2 /(60*60*24) +1;
                 //把天数返回去
                 return "你的会员剩余"+day+"天";
              }

            }else {
                return "你的会员已过期";
            }
            return "";
    }
    //定时判断会员 判断时间是否过期
    //0 5 3 * * ?    0 0 0 * * ?
    @Scheduled(cron = "0 51 13 * * ?")
    public void selectMember(){
        List<Member> list=memberService.selectAll();
        System.out.println("我的============="+list.size());
        for (int i = 0; i <list.size() ; i++) {
            Date date = list.get(i).getDuetime();
            Date date1 = new Date();
//            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            String s=simpleDateFormat.format(date);
//            System.out.println(s);
//            try {
//                date1=simpleDateFormat.parse(s);
//            } catch (ParseException e) {
//                e.printStackTrace();
//            }
            System.out.println("结束时间"+date);
            long nowTime = System.currentTimeMillis();
            long a=date.getTime()-8*60*60*24*1000;
            System.out.println("当前时间====="+nowTime);
            System.out.println("结束时间====="+a);
            if (nowTime >=a) {
                System.out.println("哈哈哈哈==========");
                User user = new User();
                user.setUserid(list.get(i).getUserid());
                user.setMember(1);
                userService.updateByUserId(user);
                memberService.deleteByPrimaryKey(list.get(i).getMemberid());
            }
        }
         List<Usercoupon> list1=userCouponService.select();
        for (int i = 0; i <list1.size() ; i++) {
            if (list1.get(i).getCouponstatu()==0){
                long endTime=list1.get(i).getEndtrme().getTime()-8*60*60*24*1000;
                Date date=new Date();
                long nowTime=date.getTime();
                if (nowTime>=endTime){
                    Usercoupon usercoupon=new Usercoupon();
                    usercoupon.setCouponstatu(2);

                }
            }
        }
    }
    @RequestMapping(value = "/chongzhi",method =RequestMethod.GET)
    @ApiOperation(value = "充值余额",notes = "充值余额")
    @ApiImplicitParam(name = "money",value = "充值金额")
    private String chongzhiy(HttpServletRequest httpRequest, HttpServletResponse httpResponse,HttpSession session,double money) throws IOException, AlipayApiException {
            long dingdan=System.currentTimeMillis();
            Long a=dingdan++;
            String hao=a.toString();
            String URL="https://openapi.alipay.com/gateway.do";
            String APP_ID="2019022063283203";
            String APP_PRIVATE_KEY="MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQC/KTaH2KSLJyWF9wXl8pmbNV92q7jGQw0HqkA19LYXl4tCg9gGTE5AWa1w+BmQT/N96QO20Mli2zyh03YlwNgg0eUkk7caC6DcWK4vg9FS7y/xTzMzXXjeUyA3qoeDx2G7ou7RYPM1gP6I2FoBgSuQwRswIkyXWzbKIt71UIM4N8hYfnMJ6/K7ImiapLJh58jWCeHcjkKnSmVtp90FFqMB9grUYqwVEmurhg/33WwTgO9aEpoIMo7kgROOJpecPnKhtnaQoHLcjw0S87as25brw94ojOMYiDg/NQ+hpmwZjPbbiMUEVAnpkDysz4uHx6MrSYcIcCxqcTzlwQfRbWkPAgMBAAECggEAFcD45aivwO4phP9BepOLC3CddoHAOz+yIecr+3fnqPOj82PRl5XjactKw4pYTmXqza9QruM/p7JPShMoZM93SPTZ4Lm2oo4kNi8ZU2rqzUdO62UZ7IR8lsBa8DrFxSdRZer6xnUD+Fi/no8QXw92B7kSAP5GPQsyRvqE6OHKrQDpj5QYJDoGd4MpCC6dQ8rGrHmZ1N4EkwJAsPqCsFn1jYfZbMpd2ZmC/3MRiQka+UbQyYDQeilSEH5oMKQLfxQLMO8IVnscE9b0207SctK1M15L54fmpvPtQzMNTZseeh777p33najAKT/fzHr0Yvoxxf0cgAvWIj947qiapLce4QKBgQDxUKw6hex89uDr7yXUUt7lzz/txPcq15UICAXxyyyBcN32f+alW2DndtCi4TPkYol+YruPT3qK/UtJR4Urk0UP+wtcbjDWsfw/PTFrcFZ00rKOmEAQrHYNnY6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whMPyRsd1uCESVJszETM6Hwk8L73xYHI9MUMwBYBvBXscTV2gNQQG0myn9AsVA1EpXFk9ykKopWtEI7XfP+adeROULIxarcyQq1FFcx6QVJLUqrIkGKYzt2efTsySfwIDAQAB";
            String SIGN_TYPE="RSA2";
            AlipayClient alipayClient = new DefaultAlipayClient(URL,APP_ID,APP_PRIVATE_KEY,FORMAT,CHARSET,ALIPAY_PUBLIC_KEY,SIGN_TYPE);
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();//创建API对应的request
            alipayRequest.setReturnUrl("http://www.baidu.com");
            alipayRequest.setNotifyUrl("http://www.baidu.com");//在公共参数中设置回跳和通知地址
            alipayRequest.setBizContent("{" +
                    "    \"out_trade_no\":\""+hao+"\"," +
                    "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
                    "    \"total_amount\":"+money+","+
                    "    \"subject\":\"每日优鲜充值\"," +
                    "    \"body\":\"每日优鲜充值\"," +
                    "    \"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\"," +
                    "    \"extend_params\":{" +
                    "    \"sys_service_provider_id\":\"2088511833207846\"" +
                    "    }"+
                    "  }");//填充业务参数
            String form="";
            try {
                form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
            } catch (AlipayApiException e) {
                e.printStackTrace();
            }
            User user= (User) session.getAttribute("user");
            Usercoupon usercoupon=new Usercoupon();
            //传入用户id
            usercoupon.setUserid(user.getUserid());
            //获取当前系统时间
            Date date=new Date();
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //设置时间格式
            String starttrme=simpleDateFormat.format(date);
            //当前时间
            Date date1=null;
        try {
            date1=simpleDateFormat.parse(starttrme);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        usercoupon.setStarttrme(date1);
        //结束时间
        long r=date1.getTime()+couponService.selectByPrimaryKey(1).getEffectivetime()*60*60*24*1000;
        String a1=simpleDateFormat.format(r);
        Date date2=null;
        try {
            date2=simpleDateFormat.parse(a1);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        usercoupon.setCouponid(1);
        usercoupon.setEndtrme(date2);
            //给用户添加优惠卷
            userCouponService.insert(usercoupon);
            /*System.out.println(form);
            orderFormService.updateOrderStatuId(orderForm.getOrderid());
            return  JSON.toJSONString(form);*/
        /*else {
            orderFormService.updateCancelled(orderForm.getOrderid());
        }*/
        if (money>=100){
            //给用户添加余额,赠送5块余额
            user.setBalance(money+5);
        }else if (money>=200){
            //给用户添加余额,赠送15块余额
            user.setBalance(money+15);
        }else if (money>=500){
            //给用户添加余额,赠送50块余额
            user.setBalance(money+50);
        }else {
            user.setBalance(money);
        }
        int money2= (int) (money*100);
        user.setIntegral(money2);
        userService.updateByUserId(user);
        return form;
    }
}
